package com.cloud.lock.web;


import com.alibaba.fastjson.JSON;
import com.cloud.lock.util.HttpClientUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/callback")
public class CallBackController {


    @RequestMapping("/")
    public Object callback(@RequestParam String code) {
        String url = "http://127.0.0.1:8080/oauth/token";

        Map<String, String> paramMap = new HashMap<String, String>();

        paramMap.put("client_id", "app01");
        paramMap.put("client_secret", "app01");
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("code", code);
        paramMap.put("redirect_uri", "http://127.0.0.1:8868/callback/");

        Object result = HttpClientUtil.doPost(url, paramMap);

        Map<String, String> resultMap = (Map) JSON.parse((String) result);

        String accessToken = resultMap.get("access_token");

        String userInfoUrl = "http://127.0.0.1:8080/oauth/user/info";

        Map<String, String> userInfoMap = new HashMap<String, String>();
        userInfoMap.put("token", accessToken);


        /* HttpHeaders headers = new HttpHeaders();
        // headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<Map> request = new HttpEntity<>(paramMap, headers);
        ResponseEntity<String> response = new RestTemplate().postForEntity(url, request, String.class);
        */
        return HttpClientUtil.doPost(userInfoUrl, userInfoMap);
    }

}
